package com.bdqn;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class ShortAnswer3_upd {
    public static void main(String[] args) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse("src/main/java/com/bdqn/Student.xml");


            // 获取student元素节点
            NodeList nodeList = document.getElementsByTagName("student");
            // 循环判断找出id=2的把成绩该为60
            for (int i = 0; i < nodeList.getLength() ; i++) {
                Element element = (Element) nodeList.item(i);
                String id = element.getAttribute("id");
                if (Integer.parseInt(id) == 2) {
                    if (element.getNodeType() == Node.ELEMENT_NODE){
                        NodeList nodeList1 = element.getChildNodes();
                        for (int j = 0; j < nodeList1.getLength(); j++) {
                            Node item = nodeList1.item(j);
                            String nodeName = item.getNodeName();
                            if (nodeName.equals("score")){
                                item.setTextContent("60");
                                System.out.println("修改成功");
                            }
                        }


                    }

                }

            }

            // 保存XML文件
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource domSource = new DOMSource(document);
            // 设置编码类型
            transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
            StreamResult result = new StreamResult(new FileOutputStream("src/main/java/com/bdqn/Student.xml"));
            // 把DOM树转换为XML文件
            transformer.transform(domSource,result);

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}
